#include "skinwindow.h"
#include "ui_skinwindow.h"
#include <QDesktopWidget>
#include <QPropertyAnimation>
#include <QParallelAnimationGroup>
#include <QVBoxLayout>
#include <QPainter>
#include "controls/titlebar.h"
#include "common.h"


SkinWindow::SkinWindow(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::SkinWindow)
{
    ui->setupUi(this);

    // 设置窗口透明
    this->setWindowOpacity(0);
    // 关闭就自我析构
    setAttribute(Qt::WA_DeleteOnClose);
    // 去边框
    setWindowFlags(Qt::Dialog | Qt::FramelessWindowHint | windowFlags());
    initSkinWindow();
}

void SkinWindow::initSkinWindow()
{
    // 创建标题栏对象
    TitleBar* pBar = new TitleBar(true);
    // 窗口标题
    pBar->setTitleName("360皮肤中心");
    // 设置拖动标题栏窗口跟随移动
    pBar->setMoveable(true);
    // 设置拖动标题栏的时候哪个窗口跟随移动
    pBar->setMainWindow(this);
    QVBoxLayout* vlayout = static_cast<QVBoxLayout*>(layout());
    // 标题栏插入到窗口布局中
    vlayout->insertWidget(0, pBar);

    connect(pBar, &TitleBar::minimumWin, this, &SkinWindow::showMinimized);
    connect(pBar, &TitleBar::closeWin, this, &SkinWindow::close);
}

void SkinWindow::showWgAnimation()
{
    show();
    QPropertyAnimation* pAnimation1 = new QPropertyAnimation(this, "geometry");
    QDesktopWidget* pDeskWg = QApplication::desktop();
    int x = (pDeskWg->availableGeometry().width() - width()) / 2;
    int y = (pDeskWg->availableGeometry().height() - height()) / 2;
    pAnimation1->setDuration(1000);  // 动画事件为1s
    pAnimation1->setStartValue(QRect(x, y+100, width(), height()));
    pAnimation1->setEndValue(QRect(x, y, width(), height()));
    pAnimation1->setEasingCurve(QEasingCurve::OutElastic);

    QPropertyAnimation *pAnimation2 = new QPropertyAnimation(this, "windowOpacity");
    pAnimation2->setDuration(1000);
    pAnimation2->setKeyValueAt(0.3, 0.5);
    pAnimation2->setKeyValueAt(1, 1);

    QParallelAnimationGroup *group = new QParallelAnimationGroup(this);
    group->addAnimation(pAnimation1);
    group->addAnimation(pAnimation2);
    group->start(QAbstractAnimation::DeleteWhenStopped);
}

void SkinWindow::paintEvent(QPaintEvent *e)
{
    QPainter painter(this);
    QString img = Common::getInstance()->getBackgroundImage();
    painter.drawPixmap(0, 0, width(), height(), QPixmap(img));
}

SkinWindow::~SkinWindow()
{
    delete ui;
}
